package com.deuwise.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.base.Tree;
import com.deuwise.common.utils.FileUtil;
import com.deuwise.system.entity.*;
import com.deuwise.system.entity.from.SortModel;
import com.deuwise.system.entity.vo.LayerVo;
import com.deuwise.system.service.*;
import io.swagger.annotations.*;
import io.swagger.annotations.ApiImplicitParams;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.baomidou.mybatisplus.plugins.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 *@author hezhenhao
 *@date 2020-05-20 15:41:55
 */
@Api(tags = "图层管理模块", description = "图层管理")
@RequestMapping("system/syslayer")
@RestController()
public class SysLayerController extends AbstractController{
    @Autowired
    private SysLayerService sysLayerService;
    @Autowired
    private LayerTypeDoService layerTypeDoService;
    @Autowired
    private SysLayerDictService sysLayerDictService;
    /**应用-图层关联关系*/
    @Autowired
    private SysSiteLayerService layerService;
    @Autowired
    private AppDoService appDoService;

    @ApiOperation(value = "获取list", notes = "")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<SysLayer>> list(@RequestParam(required = false) SysLayer syslayer){
        Wrapper<SysLayer> wrapper = new EntityWrapper<SysLayer>();

        Page<SysLayer> listPage = sysLayerService.selectPage(getPage(SysLayer.class),wrapper);
        return Result.ok(listPage);
    }

    @ApiOperation(value = "新增图层分组")
    @RequestMapping(value = "/insertSyslayer", method = RequestMethod.POST)
    public R insertSyslayer(@RequestBody SysLayer syslayer){
        boolean isSuccess = false;
        if(null == syslayer){
            return R.error(200,"新增数据失败，请稍后再试!");
        }
        SysLayer syslayer1 = selectParam(null,null, syslayer.getLayerTitle(), null);
        if(null != syslayer1 && StringUtils.isBlank(syslayer1.getLayerType())){
            return R.error(200,"新增数据失败，图层分组已存在!");
        }
        syslayer.setParentId("0");
        isSuccess = sysLayerService.insert(syslayer);
        if (isSuccess) {
            return R.ok(syslayer);
        } else {
            return R.error(200,"新增数据失败，请稍后再试!");
        }
    }

    @ApiOperation(value = "编辑图层分组")
    @RequestMapping(value = "/updateSyslayer", method = RequestMethod.POST)
    public R updateSyslayer(@RequestBody SysLayer syslayer){
        boolean isSuccess = false;
        if(null == syslayer){
            return R.error(200,"数据编辑失败，请稍后再试!");
        }
        SysLayer syslayer1 = selectParam(null,null, syslayer.getLayerTitle(), null);
        if(null != syslayer1 && !syslayer1.getId().equals(syslayer.getId())
                && StringUtils.isBlank(syslayer1.getLayerType())){
            return R.error(200,"数据编辑失败，图层分组已存在!");
        }
        syslayer.setParentId("0");
        isSuccess = sysLayerService.updateById(syslayer);
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(200,"数据编辑失败，请稍后再试!");
        }
    }

    @GetMapping("/addJsonModel")
    @ApiOperation(value = "获取新增图层模板(JSON/表单模式)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "layerType", value = "图层类型", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "version", value = "版本号", dataType = "String", paramType = "query", required = true)})
    public Result<JSONObject> addJsonModel(String layerType, String version){
        Wrapper<SysLayerDict> wrapper = new EntityWrapper<SysLayerDict>();
        wrapper.eq("layer_type", layerType);
        wrapper.eq("version", version);
        List<SysLayerDict> doList=  sysLayerDictService.selectList(wrapper);

        if(null == doList || 0 == doList.size()){
            return Result.build(500, "该图层类型在图层字典中不存在!");
        }
        Class cls = SysLayerDict.class;
        //获取父节点属性是public的
        Field[] fields = cls.getFields();
        JSONObject jsonObject=new JSONObject(new LinkedHashMap());
        for(int i=0; i<fields.length; i++){
            Field f = fields[i];
            if(f.getName().equals("parentId")){
                jsonObject.put(f.getName(),0);
            }else if(f.getName().equals("visible")){
                jsonObject.put(f.getName(),true);
            }else if(f.getName().equals("sort")){
                jsonObject.put(f.getName(),0);
            }
            else {
                jsonObject.put(f.getName(), "");
            }
        }
        for (SysLayerDict sysLayerDict : doList){
            jsonObject.put(sysLayerDict.getField(),"");
        }
        jsonObject.put("layerTypeId",layerType);
        jsonObject.put("type",layerType);
        return Result.ok(jsonObject);
    }

    /**
     * 获取编辑的图层信息
     */
    @ApiOperation(value = "根据ID获取编辑的图层信息", notes = "")
    @RequestMapping(value = "/getLayerInfoById", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键标识", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "showAll", value = "是否显示所有(包含空值),0:否,1:是", defaultValue = "0", dataType = "int", paramType = "query")})
    public Result<SysLayer> getLayerInfoById(String id, int showAll) {
        SysLayer sysLayer = sysLayerService.selectById(id);

        if(null != sysLayer){
            JSONObject jsonObjectData = JSONObject.parseObject(sysLayer.getLayerDataStr());
            if(null == jsonObjectData){
                return Result.ok(sysLayer);
            }
            // 图层信息字符串类型不需返回
            sysLayer.setLayerDataStr("");
            if(1 == showAll){
                // 根据layerName 获取对应图层字典
                Result<JSONObject> result = addJsonModel(sysLayer.getLayerType(), sysLayer.getVersion());
                JSONObject jsonObject =result.getData();
                // 附加空值的属性
                for(String k : jsonObjectData.keySet()){
                    Object value = jsonObjectData.get(k);
                    if(jsonObject.containsKey(k)){
                        // 存在，赋值
                        jsonObject.put(k, value);
                    }
                }
                sysLayer.setLayerDataJson(jsonObject);
            }
            if(0 == showAll){
                // 过滤空值
                JSONObject jsonObject = new JSONObject();
                // 附加空值的属性
                for(String k : jsonObjectData.keySet()){
                    Object value = jsonObjectData.get(k);
                    if(null != value){
                        jsonObject.put(k, value);
                    }
                }
                sysLayer.setLayerDataJson(jsonObject);
            }
        }

        return Result.ok(sysLayer);
    }

    @ApiOperation(value = "json类型新增")
    @RequestMapping(value = "/insertLayerJson", method = RequestMethod.POST)
    public R insertLayerJson(@RequestBody LayerVo layerVo){
        try {
            if (null == layerVo || null == layerVo.getLayerDataJson()) {
                return R.error(500, "图层信息不能为空！");
            }
            JSONObject jsonObject = layerVo.getLayerDataJson();
            SysLayer sysLayer1 = new SysLayer();
            sysLayer1.setVersion(layerVo.getVersion());
            sysLayer1.setLayerId(jsonObject.get("id") == null ? "" : jsonObject.get("id").toString());
            sysLayer1.setLayerDataJson(jsonObject);
            sysLayer1.setLayerType(jsonObject.get("type") == null ? "" : jsonObject.get("type").toString());
            sysLayer1.setLayerTitle(jsonObject.get("title") == null ? "" : jsonObject.get("title").toString());
            sysLayer1.setParentId(layerVo.getParentId());
            sysLayer1.setLayerDataStr(jsonObject.toJSONString());

            if (StringUtils.isBlank(sysLayer1.getLayerType())) {
                return R.error(500, "图层类型不能为空！");
            }
            if (StringUtils.isNotBlank(layerVo.getId())) {
                sysLayer1.setId(layerVo.getId());
            }
            // 判断图层类型是否存在
            Wrapper<LayerTypeDo> wrapper = new EntityWrapper<>();
            wrapper.eq("value", sysLayer1.getLayerType());
            LayerTypeDo layerTypeDo = layerTypeDoService.selectOne(wrapper);
            if(null == layerTypeDo){
                return R.error(500, "图层类型(type)在API中不存在！");
            }
            // 判断是否有重复的图层
            SysLayer sysLayer2 = selectParam(sysLayer1.getLayerType(), sysLayer1.getLayerId(), sysLayer1.getLayerTitle(), sysLayer1.getVersion());
            if(null != sysLayer2){
                sysLayer1.setId(sysLayer2.getId());
            }
            sysLayer1.setLayerName(layerTypeDo.getName());
            sysLayerService.insertOrUpdate(sysLayer1);
            return R.ok(sysLayer1);
        }catch (Exception ex){
            return  R.error(ex.toString());
        }
    }

    @ApiOperation("删除字典")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") String id){
        sysLayerService.deleteById(id);
        return R.ok();
    }

    @ApiOperation("排序菜单")
    @PostMapping("/sortMenu")
    public R sortMenu(@RequestBody List<SortModel> list){
        //数据校验
        //ValidatorUtils.validateEntity(sortModel, UpdateGroup.class);
        List<SysLayer> sysMenuList=new ArrayList<>();
        for(SortModel sortModel:list){
            SysLayer menu=new SysLayer();
            menu.setId(sortModel.getId());
            menu.setOrderNum(sortModel.getOrderNum());
            sysMenuList.add(menu);
        }
        sysLayerService.updateBatchById(sysMenuList);

        return R.ok();
    }


    @ApiOperation(value = "批量导入图层",notes = "模板下载地址=/layer.json")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "version",required = true,value = "版本号", defaultValue = "4.15", dataType = "String", paramType = "query")
    })
    @PostMapping(value = "/importLayer", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public R importLayer(@ApiParam(value = "上传文件", required = true) MultipartFile file, String version) {
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.contains(".json")) {
                return R.error("导入的文件格式不正确");
            }
        } catch (Exception e) {
            return R.error("导入的文件格式不正确");
        }
        try {
            Map<String, String> layerTypeMap = getLayerType();
            StringBuilder sb = FileUtil.getJsonStr(file);
            JSONArray jsonArray = JSON.parseArray(sb.toString());
            for (Integer i = 0; i <= jsonArray.size() - 1; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String layerTitle = jsonObject.getString("title");
                String layerType1 = jsonObject.getString("type");
                String layerVersion1 = jsonObject.getString("version");
                String layerId = jsonObject.getString("id");
                // 图层分组ID(图层信息的父级ID)
                String groupId = "";
                if(StringUtils.isNotBlank(layerTitle)){
                    // 图层分组名称
                    SysLayer sysLayer1 = selectParam(layerType1,null, layerTitle, layerVersion1);
                    if(null == sysLayer1){
                        // 图层分组不存在
                        sysLayer1 = new SysLayer();
                        sysLayer1.setParentId("0");
                        sysLayer1.setLayerTitle(layerTitle);
                        sysLayer1.setVersion(version);
                        sysLayer1.setOrderNum(0);
                    }
                    sysLayer1.setVersion(version);
                    sysLayerService.insertOrUpdate(sysLayer1);
                    groupId = sysLayer1.getId();
                }else{
                    return R.error(200, "导入错误,图层分组不能为空！");
                }
                if (jsonObject.containsKey("children")) {
                    JSONArray childJsonArray = jsonObject.getJSONArray("children");
                    for (Integer j = 0; j <= childJsonArray.size() - 1; j++) {
                        JSONObject childObject = childJsonArray.getJSONObject(j);
                        String layerTitle1 = childObject.getString("title");
                        String layerId1 = childObject.getString("id");
                        String layerType = childObject.getString("type");
                        if(StringUtils.isEmpty(layerType)){
                            return R.error(200, "导入图层type不能为空！");
                        }
                        SysLayer syslayer2 = selectParam(layerType,layerId1, layerTitle1, version);
                        if(null == syslayer2){
                            syslayer2 = new SysLayer();
                        }
                        syslayer2.setLayerTitle(layerTitle1);
                        syslayer2.setLayerType(layerType);
                        syslayer2.setLayerId(layerId1);
                        syslayer2.setLayerDataStr(childObject.toJSONString());
                        syslayer2.setParentId(groupId);
                        syslayer2.setVersion(version);
                        if(layerTypeMap.containsKey(layerType)){
                            syslayer2.setLayerName(layerTypeMap.get(layerType));
                        }
                        sysLayerService.insertOrUpdate(syslayer2);
                    }
                }
                // 不存在子项图层，并且图层类型不为空，则默认当前分组为图层
                if(!jsonObject.containsKey("children") && StringUtils.isNotBlank(layerType1)){
                    if(StringUtils.isBlank(layerId)){
                        return R.error(200, layerTitle + "图层id不能为空！");
                    }
                    if(StringUtils.isBlank(layerType1)){
                        return R.error(200, layerTitle + "图层类型不能为空！");
                    }
                    SysLayer syslayer2 = new SysLayer();
                    syslayer2.setLayerTitle(layerTitle);
                    syslayer2.setLayerType(layerType1);
                    syslayer2.setLayerId(layerId);
                    syslayer2.setLayerDataStr(jsonObject.toJSONString());
                    syslayer2.setParentId("0");
                    syslayer2.setVersion(version);
                    syslayer2.setOrderNum(0);
                    if(layerTypeMap.containsKey(layerType1)){
                        syslayer2.setLayerName(layerTypeMap.get(layerType1));
                    }
                    sysLayerService.insertOrUpdate(syslayer2);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return  R.ok();
    }

    @ApiOperation("导出图层")
    @GetMapping("/exportLayer")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ids",required = true,value = "图层id(多个用逗号隔开)", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public List<JSONObject> exportLayer(String ids){
        List<JSONObject> objectList=new ArrayList<>();
        Wrapper<SysLayer> wrapper = new EntityWrapper<>();
        // 查询分组
        wrapper.eq("parent_id", "0");
        wrapper.orderBy("order_num", true);
        List<SysLayer> parentList = sysLayerService.selectList(wrapper);

        wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(ids)){
            wrapper.in("id", ids);
            wrapper.ne("parent_id", "0");
        }
        wrapper.orderBy("order_num", true);
        List<SysLayer> childrensList = sysLayerService.selectList(wrapper);
         int index = 0;
        for(SysLayer sysLayer : parentList){
            // 根据图层组查找下级图层
            List<SysLayer> childrenList = childrensList.stream().filter(f->f.getParentId() != null && f.getParentId().equals(sysLayer.getId())).collect(Collectors.toList());
            if(0 == childrenList.size() && StringUtils.isBlank(sysLayer.getLayerType()) && StringUtils.isBlank(sysLayer.getLayerId())){
                continue;
            }
            // 组装图层分组信息
            JSONObject jsonObject = new JSONObject(16, true);
            jsonObject.put("id", index);
            jsonObject.put("title", sysLayer.getLayerTitle());
            jsonObject.put("visible", true);
            jsonObject.put("sort", sysLayer.getOrderNum());
            if(childrenList!=null && childrenList.size()>0){
                List<JSONObject> children=new ArrayList<>();
                for(SysLayer sysLayer1 : childrenList){
                    JSONObject child= JSONObject.parseObject(sysLayer1.getLayerDataStr());
                    if(null == child){
                        child = new JSONObject();
                    }
                    child.put("uuid", sysLayer1.getId());
                    children.add(child);
                }
                jsonObject.put("children",children);
            }
            if(childrenList != null && childrenList.size() > 0) {
                objectList.add(jsonObject);
            }
            // 更节点为图层时
            if(childrenList.size() == 0 && StringUtils.isNotBlank(sysLayer.getLayerType())
                    && StringUtils.isNotBlank(sysLayer.getLayerId()) && -1 < ids.indexOf(sysLayer.getId())){
                JSONObject layerObj= JSONObject.parseObject(sysLayer.getLayerDataStr());
                objectList.add(layerObj);
            }
            index++;
        }
        return  objectList;
    }

    @ApiOperation("根据系统ID导出对应图层")
    @GetMapping("/exportLayerBySiteId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteId",required = true,value = "系统ID", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public Map<String,List<JSONObject>> exportLayerBySiteId(String siteId){
        Map<String, List<JSONObject>> resultMap = new HashMap<>(16);
        Wrapper<SysSiteLayer> wrapper=new EntityWrapper<>();
        wrapper.eq("site_id",siteId);
        List<SysSiteLayer> siteLayerList = layerService.selectList(wrapper);
        // 二维的图层id
        List<SysSiteLayer> layerList2d = siteLayerList.stream().filter(f->f.getCategory() != null && f.getCategory().equals("2d")).collect(Collectors.toList());
        // 三维的图层id
        List<SysSiteLayer> layerList3d = siteLayerList.stream().filter(f->f.getCategory() != null && f.getCategory().equals("3d")).collect(Collectors.toList());
        // 二维图层
        StringBuffer sb = new StringBuffer();
        for(SysSiteLayer siteLayer : layerList2d){
            sb.append(siteLayer.getLayerId()).append(",");
        }
        resultMap.put("2d", new ArrayList<JSONObject>());
        if(StringUtils.isNotBlank(sb.toString())){
            resultMap.put("2d", exportLayer(sb.toString()));
        }

        // 三维图层
        sb = new StringBuffer();
        for(SysSiteLayer siteLayer : layerList3d){
            sb.append(siteLayer.getLayerId()).append(",");
        }
        resultMap.put("3d", new ArrayList<JSONObject>());
        if(StringUtils.isNotBlank(sb.toString())){
            resultMap.put("3d", exportLayer(sb.toString()));
        }
        return resultMap;
    }

    @GetMapping("/tree")
    @ResponseBody
    @ApiOperation("查询图层树形数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "version", value = "版本号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "layerTitle", value = "图层名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "layerType", value = "图层类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "layerName", value = "图层类型名称", dataType = "String", paramType = "query")})
    public R tree(String version,String layerTitle, String layerType, String layerName) {
        List<Tree<SysLayer>> treeList=new ArrayList<>();
        // 查询所有图层
        SysLayer sysLayerQuery = new SysLayer();
        if(StringUtils.isNotBlank(version)){
            sysLayerQuery.setVersion(version);
        }
        if(StringUtils.isNotBlank(layerName)){
            sysLayerQuery.setLayerName(layerName);
        }
        if(StringUtils.isNotBlank(layerTitle)){
            sysLayerQuery.setLayerTitle(layerTitle);
        }
        if(StringUtils.isNotBlank(layerType)){
            sysLayerQuery.setLayerType(layerType);
        }
        List<SysLayer> list = sysLayerService.syslayerTreeList(sysLayerQuery);
        try{
            for(SysLayer sysLayer : list){
                if("0".equals(sysLayer.getParentId())){
                        Tree<SysLayer> tree = new Tree<>();
                        tree.setId(sysLayer.getId());
                        tree.setParentId(sysLayer.getParentId());
                        tree.setText(sysLayer.getLayerTitle());
                        Map<String, Object> state = new HashMap<>(16);
                        state.put("opened", false);
                        /*组装属性信息*/
                        Map<String, Object> map=new HashMap<>(16);
                        map.put("version",sysLayer.getVersion());
                        map.put("layerName",sysLayer.getLayerName());
                        map.put("layerTitle",sysLayer.getLayerTitle());
                        map.put("layerId",sysLayer.getLayerId());
                        map.put("sort",sysLayer.getOrderNum());
                        map.put("layerDataJson",JSONObject.parseObject(sysLayer.getLayerDataStr()));
                        tree.setState(state);
                        tree.setAttributes(map);
                        Tree<SysLayer> tree1 = findChild(tree,list);
                        // 无任何条件时:
                        if(StringUtils.isBlank(layerTitle) && StringUtils.isBlank(layerType) && StringUtils.isBlank(version)){
                            treeList.add(tree1);
                        }else{
                            // 进入条件状态
                            // 有子节点，
                            if(0 < tree1.getChildren().size()){
                                treeList.add(tree1);
                            }
                            // 没子节点，父节点符合条件的
                            if(StringUtils.isNotBlank(layerTitle) && -1 < tree1.getText().indexOf(layerTitle) && StringUtils.isNotBlank(layerTitle)){
                                treeList.add(tree1);
                            }
                            if(StringUtils.isNotBlank(layerType)  && StringUtils.isNotBlank(sysLayer.getLayerType()) && layerType.equals(sysLayer.getLayerType())){
                                treeList.add(tree1);
                            }
                        }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok(treeList);
    }

    static Tree<SysLayer> findChild(Tree<SysLayer> tree, List<SysLayer> list){
        try{
            for(SysLayer layer : list){
                if(layer.getParentId().equals(tree.getId())){
                    Tree<SysLayer> childrenTree = new Tree<>();
                    if(null != tree.getChildren() && 0 == tree.getChildren().size()){
                        tree.setChildren(new ArrayList<Tree<SysLayer>>());
                    }
                    /*组装属性信息*/
                    Map<String, Object> map=new HashMap<>(16);
                    map.put("version",layer.getVersion());
                    map.put("layerType",layer.getLayerType());
                    map.put("layerName",layer.getLayerName());
                    map.put("layerTitle",layer.getLayerTitle());
                    map.put("layerId",layer.getLayerId());
                    map.put("layerDataJson",JSONObject.parseObject(layer.getLayerDataStr()));
                    map.put("sort",layer.getOrderNum());
                    childrenTree.setId(layer.getId());
                    childrenTree.setText(layer.getLayerTitle());
                    childrenTree.setParentId(layer.getParentId());
                    childrenTree.setAttributes(map);
                    tree.getChildren().add(childrenTree);
                    findChild(childrenTree,list);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return tree;
    }

    @ApiOperation(value = "获取图层json(gis使用)")
    @GetMapping("/usetree")
    public Result<List<JSONObject>> useTree(@RequestParam(value = "version",required = false)String version,@RequestParam(value = "dimension",required = false)String dimension,@RequestParam(value = "code",required = false)String code) {
        List<String> list =null;
        List<JSONObject> jsonObjects = new ArrayList<>();
        try{
            if(StringUtils.isNotBlank(code)) {
                Wrapper<AppDo> appDoWrapper = new EntityWrapper<>();
                appDoWrapper.eq("code", code);
                AppDo appDo = appDoService.selectOne(appDoWrapper);

                if (appDo == null) {
                    return Result.ok(jsonObjects);
                }
                list = layerService.queryLayerList(appDo.getId(), dimension);
                if (list == null || list.size() == 0) {
                    return Result.ok(jsonObjects);
                }
            }
            String ids = StringUtils.join(list,",");
            jsonObjects = exportLayer(ids);
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return Result.ok(jsonObjects);
    }

    @ApiOperation(value = "图层版本升级(降级)属性比对结果")
    @RequestMapping(value = "/versionComparisonByGroupId", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="version1",value = "当前版本号",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name="version2",value = "目标版本号",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "layerGroupId", value = "图层分组ID",  dataType = "string", paramType = "query", required = true)
    })
    public R versionComparisonByGroupId(String version1, String version2, String layerGroupId) {
        if (StringUtils.isBlank(version1) || StringUtils.isBlank(version2)) {
            return R.error(200, "当前版本号与目标版本号不能为空!");
        }
        if (StringUtils.isBlank(layerGroupId)) {
            return R.error(200, "图层分组ID不能为空!");
        }
        Map<String, Map<String, String>> resMap = new LinkedHashMap<>(16);
        Wrapper<SysLayer> wrapper = new EntityWrapper<SysLayer>();
        wrapper.eq("parent_id", layerGroupId);
        List<SysLayer> list = sysLayerService.selectList(wrapper);
        for(SysLayer sysLayer : list){
            Map<String,String> map = dictComparisonBylayerType(sysLayer.getLayerType(), version1, version2, false);
            if(1 < map.size()){
                resMap.put(sysLayer.getLayerName(), map);
            }
        }
        return R.ok(resMap);
    }

    /**
     * 按条件查询图层
     * @param layerType
     * @param layerId
     * @param layerTitle
     * @return
     */
    public SysLayer selectParam(String layerType, String layerId, String layerTitle, String version){
        Wrapper<SysLayer> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(layerId)){
            wrapper.eq("layer_id", layerId);
        }
        if(StringUtils.isNotBlank(layerType)){
            wrapper.eq("layer_type", layerType);
        }
        if(StringUtils.isNotBlank(layerTitle)){
            wrapper.eq("layer_title", layerTitle);
        }
        if(StringUtils.isNotBlank(version)){
            wrapper.eq("version", version);
        }
        List<SysLayer> list = sysLayerService.selectList(wrapper);
        if(0 < list.size()){
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取图层列表
     * @return
     */
    public Map<String, String> getLayerType(){
        Map<String, String> resMap = new HashMap<>(16);
        List<LayerTypeDo> list = layerTypeDoService.selectList(new EntityWrapper<LayerTypeDo>());
        for(LayerTypeDo layerTypeDo : list){
            resMap.put(layerTypeDo.getValue(), layerTypeDo.getName());
        }
        return resMap;
    }

    /**
     * 按图层比对
     * @param layerType 图层类型
     * @param version1 版本号1
     * @param version2 版本号2
     * @return
     */
    public Map<String,String> dictComparisonBylayerType(String layerType, String version1, String version2, boolean isFiledAll){
        // 版本号1
        Map<String, String> param = new HashMap<>(16);
        param.put("version", version1);
        param.put("layerType", layerType);
        List<String> list1 = sysLayerDictService.layerFieldList(param);

        param.put("version", version2);
        List<String> list2 = sysLayerDictService.layerFieldList(param);

        Map<String,String> map = new LinkedHashMap<>(16);
        map.put(version1, version2);
        for(String field : list1){
            /*判断是否存在*/
            boolean flge = list2.stream().anyMatch(f -> field.trim().equals(f.trim()));
            if(flge){
                // 过滤掉相同字段
                if(isFiledAll){
                    map.put(field, field);
                }
                if(0 < list2.size()){
                    list2.remove(field);
                }
            }else{
                /*不存在，版本1多出的字段*/
                map.put(field, "add_field");
            }
        }

        for(int i = 0;i< list2.size();i++){
            /*版本1多出的字段*/
            map.put("add_field_" + i, list2.get(i));
        }
        return map;
    }
}